package com.example.prototipoasincrono.async;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class ServiceGestion extends Service {

	Hilo hilo;
	MiTask task;
	Cliente cliente;
	
	private final IBinder mBinder = new LocalBinder();
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}
	
	public Handler handlerConexion = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			sendRespuesta((String)msg.obj);
		}
		
	};
	
	class MiAsyncTask extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... arg0) {
			// TODO Auto-generated method stub
			return null;
		}
    	
    }
	
	public class LocalBinder extends Binder  {
		public ServiceGestion getService() {
			return ServiceGestion.this;
		}
	}
	
	public void iniciarHilo(){
    	hilo = new Hilo();
    	hilo.start();
    }
    
    public void iniciarAsync(){
    	Log.d("SERVICE", "Iniciamos async");
    	if (task==null){
	    	task = new MiTask();
	    	task.execute();
    	} else {
    		task.cancel(true);
    		task = null;
    	}
    }
    
    public void iniciarService(){
    	
    }
    
    public void finalizarHilo(){
    	hilo.interrupt();
    }
    
    public void finalizarAsync(){
    	task.cancel(true);
    }
    
    public void hacerAlgoAsync(){
    	task.ejecutarAlgo();
    }
    
    public void sendRespuesta(String txt){
    	Intent intent = new Intent("respuesta");
    	intent.putExtra("respuesta", txt);
    	LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    class Hilo extends Thread{

		@Override
		public void run() {
			Message msg = new Message();
			msg.obj="Se ha conectado mediante un hilo.";
			handlerConexion.sendMessage(msg);
			while (true) {
				try {
					Thread.sleep(10000);
					msg = new Message();
					msg.obj="Hola! Soy el hilo y sigo vivo";
					handlerConexion.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
    	
    }
    
    class MiTask extends AsyncTask<String, String, String>{

    	private int valor = 0;
		@Override
		protected String doInBackground(String... params) {
			publishProgress("Se ha conectado mediante AsyncTask");
			Log.d("ASYNC", "Que hilo?");
			while (true){
				valor++;
				if (isCancelled()) break;
				try {
					Thread.sleep(10000);
					publishProgress("Hola! Soy el AsyncTask y sigo vivo");
				} catch (InterruptedException e) {
				}
			}
			return null;
		}
		
		public void ejecutarAlgo(){
			Log.d("ASYNC", "Valor: " + valor);
			new Thread(new Runnable(){

				@Override
				public void run() {
					Log.d("ASYNC", "Otro hilo! valor_:"+ valor);
				}
				
			}).start();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			sendRespuesta(values[0]);
		}
    }

	public void iniciarKryo() {
		cliente = new Cliente(getApplicationContext());
	}
}
